package com.jlju.djmhadmin.common.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.jlju.djmhadmin.dao.common.util.UUIDUtils;
import com.jlju.djmhadmin.dao.entity.Student;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

/**
 * All rights Reserved, Designed By Liting.
 *
 * @description: 批量导入数据
 * @author: LiTing[liting08011@163.com]
 * @create: 2018-04-24 14:13
 * @Copyright ©2018 Liting. All rights reserved.
 * 注意：本内容仅限于吉林建筑大学ACM协会内部传阅，禁止外泄以及用于其他的商业用途。
 **/
public class ReadExcel {
    //总行数
    private int totalRows = 0;
    //总条数
    private int totalCells = 0;
    //错误信息接收器
    private String errorMsg;
    //构造方法
    public ReadExcel(){}
    //获取总行数
    public int getTotalRows()  { return this.totalRows;}
    //获取总列数
    public int getTotalCells() {  return this.totalCells;}
    //获取错误信息
    public String getErrorInfo() { return this.errorMsg; }

    /**
     * 读EXCEL文件，获取信息集合
     * @param mFile
     * @return
     */
    public List<Student> getExcelInfo(MultipartFile mFile) {
        String fileName = mFile.getOriginalFilename();//获取文件名
        List<Student> studentList = null;
        try {
            if (!this.validateExcel(fileName)) {// 验证文件名是否合格
                return null;
            }
            boolean isExcel2003 = true;// 根据文件名判断文件是2003版本还是2007版本
            if (ReadExcel.isExcel2007(fileName)) {
                isExcel2003 = false;
            }
            studentList = this.createExcel(mFile.getInputStream(), isExcel2003);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return studentList;
    }

    /**
     * 根据excel里面的内容读取信息
     * @param is 输入流
     * @param isExcel2003 excel是2003还是2007版本
     * @return
     * @throws IOException
     */
    public List<Student> createExcel(InputStream is, boolean isExcel2003) {
        List<Student> studentList = null;
        try{
            Workbook wb = null;
            if (isExcel2003) {// 当excel是2003时,创建excel2003
                wb = new HSSFWorkbook(is);
            } else {// 当excel是2007时,创建excel2007
                wb = new XSSFWorkbook(is);
            }
            studentList = this.readExcelValue(wb);// 读取Excel里面客户的信息
        } catch (IOException e) {
            e.printStackTrace();
        }
        return studentList;
    }

    /**
     * 读取Excel里面客户的信息
     * @param wb
     * @return
     */
    private List<Student> readExcelValue(Workbook wb) {
        // 得到第一个shell
        Sheet sheet = wb.getSheetAt(0);
        // 得到Excel的行数
        this.totalRows = sheet.getPhysicalNumberOfRows();
        // 得到Excel的列数(前提是有行数)
        if (this.totalRows > 1 && sheet.getRow(0) != null) {
            this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
        }
        List<Student> studentList = new ArrayList<Student>();
        // 循环Excel行数
        for (int r = 1; r < this.totalRows; r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }

            Student student = new Student();
//            // 循环Excel的列
            for (int c = 0; c < this.totalCells; c++) {
                Cell cell = row.getCell(c);
                if (null != cell) {
                    if (c == 0) {/** name*/
                        //如果是纯数字,比如你写的是25,cell.getNumericCellValue()获得是25.0,通过截取字符串去掉.0获得25
                        if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
//                            String id = String.valueOf(cell.getNumericCellValue());
                            String value = cell.getRichStringCellValue().getString();
                            //需要自己更改
                            student.setName(value);
                        } else {
                            student.setName("导入不存在姓名");
                        }
                    } else if (c == 1) {/** sex*/
                        if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                            //String title = String.valueOf(cell.getNumericCellValue());
                            String value = cell.getRichStringCellValue().getString();
//                            student.setAge(age.substring(0, age.length()-2>0?age.length()-2:1));
                            student.setSex(value);
                        } else {
                            student.setSex("数据导入无性别");
                        }
                    } else if (c == 2) {/** 班级*/
                        if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                            //String title = String.valueOf(cell.getNumericCellValue());
                            String value = cell.getRichStringCellValue().getString();
//                            student.setAge(age.substring(0, age.length()-2>0?age.length()-2:1));
                            student.setClassName(value);
                        } else {
                            student.setClassName("批量导入无班级");
                        }
                    } else if (c == 3) {/** 学号*/
                        if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                            //String title = String.valueOf(cell.getNumericCellValue());
                            String value = cell.getRichStringCellValue().getString();
//                            student.setAge(age.substring(0, age.length()-2>0?age.length()-2:1));
                            student.setAcNo(value);
                        } else {
                            student.setAcNo("批量导入无学号");
                        }
                    } else if (c == 4) {/** 身份证号*/
                        if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                            //String title = String.valueOf(cell.getNumericCellValue());
                            String value = cell.getRichStringCellValue().getString();
//                            student.setAge(age.substring(0, age.length()-2>0?age.length()-2:1));
                            student.setCardId(value);
                        } else {
                            student.setCardId("批量导入身份证号");
                        }
                    } else if (c == 5) {/** 年级*/
                        if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                            //String title = String.valueOf(cell.getNumericCellValue());
                            String value = cell.getRichStringCellValue().getString();
//                            student.setAge(age.substring(0, age.length()-2>0?age.length()-2:1));
                            student.setClassLevel(value);
                        } else {
                            student.setClassLevel("批量导入无年级");
                        }
                    }
                    student.setUuid(UUIDUtils.getUuid());
//                    student.setCreateDate(new Date());
                    student.setStatus("0");//状态： 代报道
                }
            }
            // 添加到list
            studentList.add(student);
        }
        return studentList;
    }

    /**
     * 验证EXCEL文件
     *
     * @param filePath
     * @return
     */
    public boolean validateExcel(String filePath) {
        if (filePath == null || !(ReadExcel.isExcel2003(filePath) || ReadExcel.isExcel2007(filePath))) {
            this.errorMsg = "文件名不是excel格式";
            return false;
        }
        return true;
    }

    // @描述：是否是2003的excel，返回true是2003
    public static boolean isExcel2003(String filePath)  {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }

    //@描述：是否是2007的excel，返回true是2007
    public static boolean isExcel2007(String filePath)  {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }
}